﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using CultuRAM.Models;
using CultuRAM.DAL;
using PagedList;

namespace CultuRAM.Controllers
{
    [Authorize]
    public class SessionController : Controller
    {
        //private readonly UnitOfWork _unitOfWork = new UnitOfWork();
        private readonly UnitOfWork _unitOfWork = EventController._unitOfWork;
        private readonly CacheMode _cacheMode = EventController._CacheMode;
        

        //
        // GET: /Session/Default

        public ActionResult Default()
        {
            return PartialView("_Default");
        }


        // 
        // GET: /Session/

        public ActionResult IndexPv(int page, int idEvent)
        {
            var lista = GetSessionsByEventIdPaged(idEvent, _cacheMode.Active, page);

            ViewBag.idEv = idEvent;

            return PartialView("_Index", lista);
        }

        // 
        // GET: /Session/Create

        public PartialViewResult CreatePv(int idEvent = 0)
        {

            Session lastOrDefault;

            if (!_cacheMode.Active)
            {
                lastOrDefault = _unitOfWork.SessionRepository.Get().LastOrDefault();
            }
            else
            {
                lastOrDefault = _cacheMode.SessionsList.Any() ?
                    _cacheMode.SessionsList.ToList().LastOrDefault() :
                    _unitOfWork.SessionRepository.Get().LastOrDefault();
            }

            var lastIdSes = lastOrDefault != null ? lastOrDefault.SessionId + 1 : 1;

            var ses = new Session()
                {
                    SessionId = lastIdSes, EventId = idEvent, Date = DateTime.Now.Date + new TimeSpan(00, 00, 0)
                };

            ViewBag.PlaceId = PopulatePlaceDropDownList();
            ViewBag.Events = PopulateEventDropDownList(idEvent);

            return PartialView("Create", ses);          
        }

        // 
        // POST: /Session/Create

        [HttpPost]
        public PartialViewResult CreatePv(Session session)
        {  
            //session.Place = _unitOfWork.PlaceRepository.GetByID(session.Place.PlaceId);
            //session.PlaceId = session.Place.PlaceId;

            if (ModelState.IsValid)
            {
                try
                {
                    if (_cacheMode.Active)
                    {
                        session.Event = _cacheMode.EventsList.ToList().FirstOrDefault(ev => ev.EventId == session.EventId);
                        _cacheMode.SessionsList.Add(session);
                    }
                    else
                    {
                        session.Event = _unitOfWork.EventRepository.GetByID(session.EventId);
                        _unitOfWork.SessionRepository.Insert(session);
                        _unitOfWork.Save();
                    }
               
                    ViewBag.MsgSuccess = "A Sessão foi registada com Sucesso!";
                    return PartialView("_Default");

                }

                catch (DataException ex)
                {
                    var error = ex;
                    ViewBag.MsgError = "Ocorreu um erro ao tentar adicionar a Sessão!";
                    return PartialView("_Default");

                }
            }

            ViewBag.PlaceId = PopulatePlaceDropDownList(session.PlaceId);
            ViewBag.Events = PopulateEventDropDownList(session.EventId);

            return PartialView("Create", session);
        }

        // 
        // GET: /Session/Edit/5

        public PartialViewResult EditPv(int id = 0)
        {
            if (id == 0)
            {
                ViewBag.MsgWarning = new MvcHtmlString("<b>ATENÇÃO:</b><br> Selecione a sessão que pretende editar, clicando numa das linhas da tabela!");
                return PartialView("_Default");
            }

            Session session = null;

            if (_cacheMode.Active)
            {
                foreach (var item in _cacheMode.SessionsList.Where(item => item.SessionId == id))
                {
                    session = item;
                    break;
                }
            }
            else
            {
                session = _unitOfWork.SessionRepository.GetByID(id);
            }


            if (session == null)
            {
                ViewBag.MsgError = "Ocorreu um erro ao tentar editar a Sessão. Certifique-se que selecionou uma sessão!";
                return PartialView("_Default");
            }


            var evId = session.EventId == 0 ? session.Event.EventId : session.EventId;

            ViewBag.Places = PopulatePlaceDropDownList(session.PlaceId);
            ViewBag.Events = PopulateEventDropDownList(session.EventId);

            return PartialView("Edit", session);
        }

        // 
        // POST: /Session/Edit/5

        [HttpPost]
        public PartialViewResult EditPv(Session session)
        {
            var evId = session.EventId == 0 ? session.Event.EventId : session.EventId;

            session.PlaceId = session.PlaceId;

            var ev = new Event();
            var listSes = new List<Session>();

            if (_cacheMode.Active)
            {
                foreach (var item in _cacheMode.EventsList.Where(item => item.EventId == evId))
                {
                    session.Event = item;
                    ev = item;
                }
                
                listSes.AddRange(_cacheMode.SessionsList.Where(item => item.EventId == evId));
                ev.EventSessions = listSes.ToList();
            }
            else
            {
                foreach (var item in _unitOfWork.EventRepository.Get().Where(item => item.EventId == evId))
                {
                    session.Event = item;
                     ev = item;
                }

                ev.EventSessions = GetSessionsByEventId(evId, _cacheMode.Active);
            }

            session.EventId = evId;
            session.Place = _unitOfWork.PlaceRepository.GetByID(session.PlaceId);

            if (ModelState.IsValid)
            {
                if (_cacheMode.Active)
                {                        
                    //Alterar a sessao nas Lista de Propriedades
                    foreach (var item in _cacheMode.SessionsList.Where(item => item.SessionId == session.SessionId))
                    {
                        _cacheMode.SessionsList.Remove(item);
                        _cacheMode.SessionsList.Add(session);
                        break;
                    }

                    /*
                    //Alterar a sessão no Evento
                    foreach (var item in ev.EventSessions.Where(item => item.SessionId == session.SessionId))
                    {
                        ev.EventSessions.Remove(item);
                        ev.EventSessions.Add(session);
                        break;
                    }*/
                }
                
                else
                {
                    _unitOfWork.SessionRepository.Update(session);
                    //_unitOfWork.EventRepository.Update(ev);
                    _unitOfWork.Save();
                }

                ViewBag.MsgSuccess = "A sessão foi alterada com sucesso!";
                return PartialView("_Default");
            }


            ViewBag.Places = PopulatePlaceDropDownList(session.PlaceId);
            ViewBag.Events = PopulateEventDropDownList(session.EventId);

            return PartialView("Edit", session);
        }

        // 
        // GET: /Session/Delete/5

        public PartialViewResult DeletePv(int id = 0)
        {
            if (id == 0)
            {
                ViewBag.MsgWarning = new MvcHtmlString("<b>ATENÇÃO:</b><br> Selecione a sessão que pretende eliminar, clicando numa das linhas da tabela!");
                return PartialView("_Default");
            }

            Session session = null;

            if (_cacheMode.Active)
            {
                foreach (var item in _cacheMode.SessionsList.Where(item => item.SessionId == id))
                {
                    session = item;
                    //eventpropertyvalue.PropertyValueId = item.PropertyValueId;
                    break;
                }
            }
            else
            {
                session = _unitOfWork.SessionRepository.GetByID(id);
            }

            if (session == null)
            {
                ViewBag.MsgError = "Ocorreu um erro ao tentar eliminar a sessão. Certifique-se que selecionou uma sessão!";
                return PartialView("_Default");
            }

            var evId = session.EventId == 0 ? session.Event.EventId : session.EventId;

            ViewBag.Places = PopulatePlaceDropDownList(session.PlaceId);
            ViewBag.Events = PopulateEventDropDownList(session.EventId);

            return PartialView("Delete", session);
        }

        // 
        // POST: /Session/Delete/5

        [HttpPost, ActionName("DeletePv")]
        public PartialViewResult DeleteConfirmedPv(Session session)
        {
            var evId = session.EventId == 0 ? session.Event.EventId : session.EventId;

            if (_cacheMode.Active)
            {
              
                foreach (var item in _cacheMode.EventsList.Where(item => item.EventId == evId))
                {
                    session.Event = item;
                }
            }
            else
            {
                //foreach (var item in _unitOfWork.EventRepository.Get().Where(item => item.EventId == evId))
                //{
                //    session.Event = item;
                //}
            }

            session.EventId = evId;

            if (ModelState.IsValid)
            {
                if (_cacheMode.Active)
                {
                    foreach (var item in _cacheMode.SessionsList.Where(item => item.SessionId == session.SessionId))
                    {
                        _cacheMode.SessionsList.Remove(item);
                        break;
                    }
                }
                else
                {
                    _unitOfWork.SessionRepository.Delete(session.SessionId);
                    _unitOfWork.Save();
                }

                ViewBag.MsgSuccess = "A propriedade foi eliminada com sucesso!";
                return PartialView("_Default");
            }


            ViewBag.Places = PopulatePlaceDropDownList(session.PlaceId);
            ViewBag.Events = PopulateEventDropDownList(session.EventId);

            return PartialView("Delete", session);
        }



        //AUXILIARY METHODS /////////////////////////////////////////////////////////

        #region Auxiliary_Methods

        //Method: Get the list of all Sessions by ID - Paged
        public IPagedList<Session> GetSessionsByEventIdPaged(int eventId, bool activeCache, int page = 1)
        {
            return activeCache ? _cacheMode.SessionsList.Where(x => x.EventId == eventId).ToPagedList(page, 5) 
                : _unitOfWork.SessionRepository.Get(filter: x => x.EventId == eventId).OrderBy(o => o.Date).ToPagedList(page,5);
        }

        //Method: Get the list of all Sessions by ID
        public IList<Session> GetSessionsByEventId(int eventId, bool activeCache, int page = 1)
        {
            return activeCache ? _cacheMode.SessionsList.Where(x => x.EventId == eventId).ToList()
                : _unitOfWork.SessionRepository.Get(filter: x => x.EventId == eventId).OrderBy(o => o.Date).ToList();
        }

        //Method: Populate the DropDownList of Places
        private SelectList PopulatePlaceDropDownList(int? selectedPlaceId = 0)
        {
            var places = _unitOfWork.PlaceRepository.GetList().OrderBy(o => o.NamePlace);
            return selectedPlaceId != 0 ? 
                new SelectList(places, "PlaceId", "NamePlace") : 
                new SelectList(places, "PlaceId", "NamePlace", selectedPlaceId);
        }
        
        //Method: Populate the DropDownList of Events
        private SelectList PopulateEventDropDownList(int? selectedEventId = 0)
        {
            var events = _unitOfWork.EventRepository.GetList();

            return selectedEventId == 0 ? 
                 new SelectList(events, "EventId", "Title") : 
                 new SelectList(events, "EventId", "Title", selectedEventId);
        }

        #endregion


    } //Class CommentController

} //Namespace CultuRAM.Controllers


